package crl.lottery.controller
{
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	
	public class ResultRequest extends EventDispatcher
	{
		private var request:URLRequest;
		
		private var  loader:URLLoader;
		
		private var _message:String;
		private var _data:String;
		public function ResultRequest()
		{
			request=new URLRequest();
			request.method=URLRequestMethod.POST;
			
			loader=new URLLoader();
			loader.dataFormat=URLLoaderDataFormat.TEXT;
			loader.addEventListener(Event.COMPLETE,completeHandler);
			loader.addEventListener(IOErrorEvent.IO_ERROR,ioErrorHandler);
		}
		
		
		private function completeHandler(event:Event):void{
			var xml:XML;
			try{
				xml=new XML(loader.data);
				var code:int=parseInt(xml.code);
				if(code==100){
					this.error(xml.message);
					return;
				}
				
			}catch(e:Error){
				this.error(e.message);
			}
			
			//todo;
			
			_message=xml.message;
			_data=xml.data;
			this.dispatchEvent(new Event(Event.COMPLETE));
		}
		
		public function get message():String{
			return _message;
		}
		
		public function get data():String{
			return _data;
		}
		
		private function error(value:String):void{
			this.dispatchEvent(new ErrorEvent(ErrorEvent.ERROR,false,false,value));
		}
		
		private function ioErrorHandler(event:IOErrorEvent):void{
			error(event.text);
		}
		
		private var istest:Boolean=false;
		public function set url(value:String):void{
			if(value==null || value==""){
				value="data/result.xml";
				istest=true;
			}else{
				istest=false;
			}
			request.url=value;
		}
		
		public function send(variables:URLVariables):void{
			if(istest==false){
				request.data=variables;
			}
			loader.load(request);
		}
	}
}